<template>
  <!-- 添加钓点模态框 -->
  <div v-if="isVisible" class="modal-overlay" @click.self="handleClose">
    <div class="modal-content">
      <div class="modal-header">
        <h3>添加钓点</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <!-- 基本信息 -->
        <div class="form-section spot-basic-info card-enhanced">
          <h4>基本信息</h4>
          
          <!-- 通用图片上传组件 -->
          <ImageUploader
            v-model:images="form.pictures"
            placeholder-text="点击添加钓点照片"
            @add="onAddPictures"
            @remove="onRemovePicture"
            @view="onViewPictures"
          />
          
          <div class="form-group">
            <label for="spot-name">钓点名称</label>
            <input
              id="spot-name"
              v-model="form.name"
              type="text"
              placeholder="请输入钓点名称"
            />
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>位置</label>
              <button class="location-btn" @click="toggleViewMode">获取位置</button>
            </div>
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="form-section spot-properties">
          <h4>详细信息</h4>
          
          <!-- 停车方便 -->
          <div class="form-group spot-parking">
            <label>停车方便(是/否):</label>
            <div class="radio-group">
              <label class="radio-option">
                <input type="radio" value="1" v-model="form.parkingEasy">
                <span>是</span>
              </label>
              <label class="radio-option">
                <input type="radio" value="0" v-model="form.parkingEasy">
                <span>否</span>
              </label>
            </div>
          </div>
          
          <!-- 是否收费 -->
          <div class="form-group spot-fee">
            <label>是否收费:</label>
            <div class="radio-group">
              <label class="radio-option">
                <input type="radio" value="1" v-model="form.isFree">
                <span>免费</span>
              </label>
              <label class="radio-option">
                <input type="radio" value="0" v-model="form.isFree">
                <span>收费</span>
              </label>
            </div>
          </div>
          
          <!-- 秘密钓点 -->
          <div class="form-group spot-secret">
            <label>秘密钓点:</label>
            <div class="radio-group">
              <label class="radio-option">
                <input type="radio" value="0" v-model="form.secret">
                <span>秘密</span>
              </label>
              <label class="radio-option">
                <input type="radio" value="1" v-model="form.secret">
                <span>公开</span>
              </label>
            </div>
          </div>
          
          <!-- 钓点等级 -->
          <div class="form-group spot-level">
            <label>钓点级别:</label>
            <div class="radio-group grid-layout" v-if="!isLoadingProps">
              <label class="radio-option" v-for="lvl in formProps.lvls" :key="lvl.code">
                <input type="radio" :value="lvl.code" v-model="form.lvls">
                <span>{{ lvl.name }}</span>
              </label>
            </div>
            <div v-else class="loading-text">加载中...</div>
          </div>
          
          <!-- 车到水距离 -->
          <div class="form-group spot-distance">
            <label>车到水距离:</label>
            <div class="radio-group grid-layout" v-if="!isLoadingProps">
              <label class="radio-option" v-for="distance in formProps.distances" :key="distance.code">
                <input type="radio" :value="distance.code" v-model="form.distance">
                <span>{{ distance.name }}</span>
              </label>
            </div>
            <div v-else class="loading-text">加载中...</div>
          </div>
          
          <!-- 水域类型 -->
          <div class="form-group spot-water-type">
            <label>水域类型:</label>
            <div class="radio-group grid-layout" v-if="!isLoadingProps">
              <label class="radio-option" v-for="waterType in formProps.waterTypes" :key="waterType.code">
                <input type="radio" :value="waterType.code" v-model="form.waterType">
                <span>{{ waterType.name }}</span>
              </label>
            </div>
            <div v-else class="loading-text">加载中...</div>
          </div>
          <!-- 鱼种 -->
          <div class="form-group spot-fish-types">
            <label>鱼类:</label>
            <div class="checkbox-group grid-layout" v-if="!isLoadingProps">
              <label class="checkbox-option" v-for="fishType in formProps.fishTypes" :key="fishType.code">
                <input type="checkbox" :value="fishType.code" v-model="form.fishTypes" />
                <span>{{ fishType.name }}</span>
              </label>
            </div>
            <div v-else class="loading-text">加载中...</div>
          </div>
          
          <!-- 钓点类型 -->
          <div class="form-group spot-types">
            <label>钓点类型:</label>
            <div class="checkbox-group grid-layout" v-if="!isLoadingProps">
              <label class="checkbox-option" v-for="spotType in formProps.spotTypes" :key="spotType.code">
                <input type="checkbox" :value="spotType.code" v-model="form.spotTypes" />
                <span>{{ spotType.name }}</span>
              </label>
            </div>
            <div v-else class="loading-text">加载中...</div>
          </div>
          
          <!-- 钓点描述 -->
          <div class="form-group desc">
            <label for="spot-description">钓点描述</label>
            <textarea
              id="spot-description"
              v-model="form.description"
              placeholder="添加对钓点的描述"
              rows="4"
            ></textarea>
          </div>
        </div>

      </div>
      <div class="modal-footer">
        <button class="btn-secondary" @click="handleReset">重置</button>
        <button class="btn-primary" @click="handleSubmit" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : '提交' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits } from 'vue';
import { invoke } from '@tauri-apps/api/core'
import ImageUploader from './ImageUploader.vue';
import { useImageProcessor } from '../composables/useImageProcessor';

interface CommonType {
  id: number;
  createdAt: string;
  updatedAt: string;
}

interface AddSpotForm {
  name: string;
  city: string;
  latitude: string;
  longitude: string;
  address: string;
  lvls: string;
  waterType: string;
  distance: string;
  price: string;
  fishTypes: string[];
  spotTypes: string[];
  imageUrl: string;
  circleId: string;
  spotId: string;
  linePointsJson: string;
  parkingEasy: number; // 1表示是，0表示否
  isFree: number; // 1表示免费，0表示收费
  secret: number; // 1表示公开，0表示秘密
  description: string; // 钓点描述
  pictures: string[]; // 图片列表
}

interface City extends CommonType {
  name: string;
  code: string;
}

interface PropType {
  code: string;
  type: number;
  name: string;
}

interface FormProps {
  lvls: PropType[];
  waterTypes: PropType[];
  fishTypes: PropType[];
  spotTypes: PropType[];
  distances: PropType[];
}

// Props
interface Props {
  isVisible: boolean;
  cities: City[];
}

defineProps<Props>();

// Emits
const emit = defineEmits<{
  close: [];
  submit: [formData: AddSpotForm];
}>();

// Form state
const form = reactive<AddSpotForm>({
  name: '',
  city: '',
  latitude: '',
  longitude: '',
  address: '',
  lvls: '',
  waterType: '',
  distance: '',
  price: 'free',
  fishTypes: [],
  spotTypes: [],
  imageUrl: '',
  circleId: '',
  spotId: '',
  linePointsJson: '',
  parkingEasy: 1, // 默认停车方便
  isFree: 1, // 默认免费
  secret: 1, // 默认公开
  pictures: [], // 图片列表
  description: '', // 钓点描述
});

const isSubmitting = ref(false);
const formProps = ref<FormProps>({
  lvls: [],
  waterTypes: [],
  fishTypes: [],
  spotTypes: [],
  distances: [],
});
const isLoadingProps = ref(false);

// 获取表单属性
async function fetchFormProps() {
  isLoadingProps.value = true;
  try {
    console.log('开始获取表单属性');
    const response = await invoke('get_spot_props') as any;
    console.log('表单属性获取成功:', response);
    
    // 解析JSON字符串数组为对象数组
    formProps.value = {
      lvls: response.lvls ? response.lvls : [],
      waterTypes: response.waterTypes ? response.waterTypes : [],
      fishTypes: response.fishTypes ? response.fishTypes : [],
      spotTypes: response.spotTypes ? response.spotTypes : [],
      distances: response.distances ? response.distances : [],
    };
    
    // 如果有数据，设置默认值
    if (formProps.value.lvls.length > 0) {
      form.lvls = formProps.value.lvls[0].code;
    }
    if (formProps.value.waterTypes.length > 0) {
      form.waterType = formProps.value.waterTypes[0].code;
    }
    if (formProps.value.distances.length > 0) {
      form.distance = formProps.value.distances[0].code;
    }
  } catch (error) {
    console.error('获取表单属性失败:', error);
    window.showToast?.('获取表单属性失败，请重试', 'error');
  } finally {
    isLoadingProps.value = false;
  }
}

// Reset form to default values
function resetForm() {
  form.name = '';
  form.city = '';
  form.latitude = '';
  form.longitude = '';
  form.address = '';
  form.fishTypes = [];
  form.spotTypes = [];
  form.imageUrl = '';
  form.circleId = '';
  form.spotId = '';
  form.linePointsJson = '';
form.parkingEasy = 1; // 默认停车方便
    form.isFree = 1; // 默认免费
    form.secret = 1; // 默认公开
    form.description = ''; // 钓点描述清空描述
  
  // 如果有数据，设置默认值
  if (formProps.value.lvls.length > 0) {
    form.lvls = formProps.value.lvls[0].code;
  }
  if (formProps.value.waterTypes.length > 0) {
    form.waterType = formProps.value.waterTypes[0].code;
  }
  if (formProps.value.distances.length > 0) {
    form.distance = formProps.value.distances[0].code;
  }
}

// Handle form submission
async function handleSubmit() {
  // Validate form inputs
  if (!form.name || !form.city || !form.latitude || !form.longitude) {
    window.showToast?.('请填写必要字段：钓点名称、城市、纬度、经度', 'info');
    return;
  }
  
  // Validate images (at least one image required)
  if (form.pictures.length === 0) {
    window.showToast?.('请至少上传一张钓点照片', 'info');
    return;
  }

  // Validate coordinates
  if (isNaN(parseFloat(form.latitude)) || isNaN(parseFloat(form.longitude))) {
    window.showToast?.('请输入有效的经纬度数值', 'info');
    return;
  }

  // Validate JSON for line points if provided
  if (form.linePointsJson) {
    try {
      JSON.parse(form.linePointsJson);
    } catch (error) {
      window.showToast?.('坐标线格式不正确，请输入有效的JSON', 'info');
      return;
    }
  }

  isSubmitting.value = true;
  try {
    // Emit the submit event with form data
    emit('submit', { ...form });
  } catch (error) {
    console.error('提交失败:', error);
    window.showToast?.('提交失败，请重试', 'error');
  } finally {
    isSubmitting.value = false;
  }
}

// Handle modal close
function handleClose() {
  emit('close');
}

const toggleViewMode = () => {
  const event = new CustomEvent('toggle-map-mode', {
    detail: { isMapMode: true, modeHandler: 'SpotAdd' }

  })
  window.dispatchEvent(event)
  console.log('钓点圈页面切换到地图模式，事件已发送')
}

// 使用图片处理器
const { processImageAndCreateTempFile } = useImageProcessor();

// 图片处理方法
async function onAddPictures() {
  try {
    // 创建隐藏的文件输入元素以弹出图片选择窗口
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.style.display = 'none';
    document.body.appendChild(input);
    
    // 等待用户选择图片
    const fileSelected = new Promise<string>((resolve, reject) => {
      input.onchange = async (event) => {
        try {
          const target = event.target as HTMLInputElement;
          if (target.files && target.files[0]) {
            const file = target.files[0];
            // 获取JWT Token
            const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
            const jwtToken = currentUser.token;
            
            if (!jwtToken) {
              reject(new Error('请先登录'));
              return;
            }
            
            try {
              // 使用通用图片处理方法处理图片并创建临时文件
              const tempFilePath = await processImageAndCreateTempFile(file);
              // 调用Rust的upload_image_file函数上传图片
              const imageUrl = await invoke('upload_image_file', { filePath: tempFilePath, jwtToken: jwtToken }) as string;
              resolve(imageUrl);
            } catch (error: any) {
              // 处理图片处理过程中的错误
              console.error('图片处理失败:', error);
              // 网络连接错误特殊处理
              if (error.message && error.message.includes('网络连接错误')) {
                reject(new Error('网络连接错误，请检查您的网络连接后重试'));
              } else {
                reject(error);
              }
            }
          } else {
            reject(new Error('未选择图片'));
          }
        } catch (error) {
          reject(error);
        } finally {
          // 清理DOM元素
          document.body.removeChild(input);
        }
      };
      
      // 触发点击事件打开图片选择窗口
      input.click();
    });
    
    const imageUrl = await fileSelected;
    if (imageUrl) {
      form.pictures.push(imageUrl);
      console.log('图片上传成功:', imageUrl);
    }
  } catch (error: any) {
    console.error('添加图片失败:', error);
    // 显示适当的错误消息
    let errorMessage = '添加图片失败，请重试';
    if (error.message) {
      errorMessage = error.message;
    }
    window.showToast?.(errorMessage, 'error');
  }
}

function onViewPictures(index: number) {
  if (form.pictures.length > 0) {
    // 在实际应用中，这里应该打开图片查看器
    console.log('查看图片索引:', index, '，所有图片:', form.pictures);
    window.showToast?.(`查看图片: ${form.pictures[index]}`, 'info');
  }
}

function onRemovePicture(index: number) {
  form.pictures.splice(index, 1);
}


// Handle form reset
function handleReset() {
  resetForm();
}

// Reset form when component is mounted
onMounted(() => {
  resetForm();
  fetchFormProps();
});
</script>

<style scoped>
/* Modal styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
}

/* Image uploader styles */
.spot-images {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  align-items: flex-start;
}

.image-placeholder {
  width: 120px;
  height: 120px;
  border: 1px dashed var(--border);
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: var(--bg-secondary);
}

.placeholder-text {
  color: var(--text-secondary);
  font-size: 12px;
  text-align: center;
  padding: 10px;
}

.main-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
  cursor: pointer;
}

.add-image-btn {
  width: 120px;
  height: 120px;
  border: 1px dashed var(--border);
  border-radius: 8px;
  cursor: pointer;
  background-color: var(--bg-secondary);
}

.thumbnail-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.thumbnail-item {
  position: relative;
  width: 80px;
  height: 80px;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.thumbnail-remove {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: var(--danger);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
}

.thumbnail-remove:hover {
  background-color: var(--danger-hover);
}

.modal-content {
  background-color: var(--bg-card);
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  width: 100%;
  max-width: 90vh;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--border);
  background-color: var(--bg-secondary);
}

.modal-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 18px;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid var(--border);
  background-color: var(--bg-secondary);
}

/* Form styles */
.loading-text {
  color: var(--text-secondary);
  font-style: italic;
  padding: 8px;
  border: 1px solid var(--border);
  border-radius: 4px;
  background-color: var(--bg-secondary);
}

.form-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

/* Card style for form groups - extending theme-card */
.form-group {
  flex: 1;
  margin-bottom: 15px;
  background-color: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 15px;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-card);
}

/* 增加描述部分的底部内边距 */
.form-group:has(textarea) {
  padding-bottom: 20px;
}

/* Extend theme-card hover effect */
.form-group:hover {
  border-color: var(--border-hover);
  box-shadow: var(--shadow-hover);
  transform: translateY(-1px);
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: var(--text-primary);
  font-size: 14px;
  font-weight: 500;
}

/* Card style for form sections - extending theme-card */
.form-section {
  background-color: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: var(--shadow-card);
  border-bottom: none;
}

.form-section h4 {
  margin: 0 0 15px 0;
  color: var(--text-primary);
  font-size: 16px;
  font-weight: 600;
}

.form-section:last-child {
  margin-bottom: 0;
}

/* Form inputs - extending theme-input */
.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px 15px;
  background-color: var(--bg-input);
  color: var(--text-primary);
  border: 2px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

/* Form element focus and hover states - extending theme-input */
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.form-group input:hover,
.form-group select:hover,
.form-group textarea:hover {
  border-color: var(--border-hover);
}

/* Enhance textarea styling - extending theme-input */
.form-group textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

/* Styling for disabled form elements - extending theme-input disabled state */
.form-group input:disabled,
.form-group select:disabled,
.form-group textarea:disabled {
  background-color: var(--bg-disabled);
  border-color: var(--border-disabled);
  color: var(--text-disabled);
  cursor: not-allowed;
}





/* 单选组和复选框组样式 - 统一样式规范 */
.radio-group,
.checkbox-group {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.radio-group.grid-layout,
.checkbox-group.grid-layout {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.radio-option,
.checkbox-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.radio-option:hover,
.checkbox-option:hover {
  border-color: var(--border-hover);
  background-color: var(--bg-secondary);
  transform: translateY(-1px);
}

/* 普通状态样式优化 - 使用全局文本次要颜色 */
.radio-option span,
.checkbox-option span {
  padding: 4px 0;
  color: var(--text-secondary);
  transition: color 0.3s ease;
}

/* 选中状态样式增强 - 使用较温和的颜色 */
.radio-option input[type="radio"]:checked + span,
.checkbox-option input[type="checkbox"]:checked + span {
  color: var(--accent-secondary);
  font-weight: 500;
}

.radio-option input,
.checkbox-option input {
  width: 18px;
  height: 18px;
  margin: 0;
  cursor: pointer;
}

.form-group input::placeholder,
.form-group textarea::placeholder {
  color: var(--text-secondary);
}

.form-note {
  font-size: 12px;
  color: var(--text-secondary);
  margin: 0 0 10px 0;
}

/* Button styles - 扩展全局按钮样式规范 */
.btn-primary,
.btn-secondary {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  min-width: 100px;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-primary {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.btn-primary:hover:not(:disabled) {
  background-color: var(--accent-primary-hover);
  transform: translateY(-1px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.btn-secondary {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
  border: 2px solid var(--border);
}

.btn-secondary:hover:not(:disabled) {
  background-color: var(--bg-card);
  border-color: var(--border-hover);
  transform: translateY(-1px);
}

/* 统一禁用状态样式 */
.btn-primary:disabled,
.btn-secondary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  background-color: var(--bg-disabled);
  color: var(--text-disabled);
  box-shadow: none;
}

/* 位置按钮样式 - 与全局按钮样式统一 */
.location-btn {
  width: 100%;
  padding: 12px 24px;
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.location-btn:hover {
  background-color: var(--accent-primary-hover);
  transform: translateY(-1px);
}

/* Close button */
.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: 24px;
  cursor: pointer;
  padding: 8px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  color: var(--text-primary);
  background-color: var(--bg-secondary);
}
</style>